var boxInfoShowMS = 1 * 1000;
var boxInfoWaitMS = 4 * 1000;
// var boxInfoHideMS = 1.5 * 1000;

var intervalShow = 250;
var intervalShowCount = 0;
var intervalShowTimerCount = null;

// canviar el menú que està actiu
function clickMenu() {
	$('.ym-hlist .active').removeClass('active');
	// mira la url i extreu quin es el menú seleccionat
	$('a[href*="' + window.location.pathname.replace('/mediateca/', '') + '"]')
			.parents('li').addClass('active');
}
// canviar les rutes per defecte i les transforma amb crides a actions per ajax
function changeActiveLinks() {
	$('.active a[id]').attr({
		'href' : '#'
	}).each(function() {
		$(this).attr("id", $(this).attr("id") + 'Ajax');
		$(this).click(loadContentAjax);
	});
}
function loadContentAjax() {
	$('.ym-hlist .active').removeClass('active');
	$(this).parents('li').addClass('active');
	var id = $(this).attr('id');
	$.ajax({

		url : id,
		type : "POST",
		beforeSend : function() {
			waitLoading(true);
		},
		complete : function() {
			setChosen(true);
			waitLoading(false);
		},
		// error: function(XMLHttpRequest, textStatus, errorThrown){
		// alert('Error ' + textStatus);
		// alert(errorThrown);
		// alert(XMLHttpRequest.responseText);
		// },
		success : function(data) {
			var response = document.createElement("div");
			$(response).html(data);
			$('#content').html($("#content", response).html());
		}
	});
}
// Loading de les crides ajax
function waitLoading(wait) {
	if (wait) {
		$("body").addClass("loading");
	} else {
		$("body").removeClass("loading");
	}
}

//
function setButtons() {
	setTimeout(function() {
		setChosen(true);
	}, 250);
}

// converteix els selects a chosen selects
function setChosen(destroy) {
	try {
		if (destroy) {
			$('select').chosen('destroy');
		}
	} catch (e) {

	}
	$('select').chosen({
		allow_single_deselect : true
	});
}

function addNew(actionName, selectName) {
	$.ajax({
		url : actionName,
		type : "POST",
		beforeSend : function() {
			waitLoading(true);
		},
		complete : function() {
			setChosen(true);
			waitLoading(false);
		},
		// error: function(XMLHttpRequest, textStatus, errorThrown){
		// alert('Error ' + textStatus);
		// alert(errorThrown);
		// alert(XMLHttpRequest.responseText);
		// },
		success : function(data) {
			var response = document.createElement("div");
			$(response).html(data);
			$('#dialogAdd').html($("#content", response).html());
			showAddDialog(selectName);
		}
	});
}

// Missatge emergent usant el toastmessage
function showInfo(type, text) {
	$().toastmessage('showToast', {
		text : text,
		sticky : false,
		position : 'top-right',
		type : type,
		closeText : ''
	});
}

function validate(id) {
	$('.ym-error').removeClass('ym-error');
	var error = 0;
	$('#' + id + ' [required]').each(function() {
		var val = $(this).val();
		var objectId = $(this).attr('id');
		if (!requiredString(val)) {
			// var txt=$.i18n.prop(id + '.requiredstring');
			// var txt=$(this).parent().find('label').text();
			setError(objectId, $.i18n.prop(objectId + '.requiredstring'));
			error++;
		}
	});
	if ($('#' + id + ' #isbn').length > 0 && $('#isbn').val()
			&& checkLength($('#isbn').val(), '13')) {
		setError("isbn", $.i18n.prop('isbn.length.error'));
		error++;
	}
	return error == 0;
}
function requiredString(value) {
	return ($.trim(value));
}

function justNumbers(e) {
	if (window.event) {
		keynum = e.keyCode;
	} else {
		keynum = e.which;
	}
	if (keynum == 8 || keynum == 0) {
		return true;
	}
	if (keynum > 47 && keynum < 58) {
		return true;
	} else {
		return false;
	}
}
function checkLength(value, length) {
	return (value.length < length);
}
function setError(input, errorText) {
	$('#' + input).parents('.ym-fbox:first').addClass("ym-error");
	showToast("error", errorText);

}
function checkError(t) {
	var obj = $(t);
	var type = $(t).attr('type');
	if (obj.attr('required')) {
		if (type == 'text') {
			if (!requiredString(obj.val())) {
				obj.val('');
				obj.parent().addClass('ym-error');
				return false;
			} else if (obj.attr('role') == 'isbn'
					&& checkLength(obj.val(), '13')) {
				showToast('error', $.i18n.prop('isbn.length.error'));
				obj.parent().addClass('ym-error');
				return false;
			}
		} else if (obj.prop('tagName') == 'SELECT') {
			if (!obj.val()) {
				obj.parents('.ym-fbox:first').addClass('ym-error');
				return false;
			}
		}
	}
	obj.parents('.ym-fbox:first').removeClass('ym-error');
}
function checkError2(name, type) {
	var obj = $('#' + name);
	if (type == 'text') {
		if (!requiredString(obj.val())) {
			obj.val('');
			obj.parent().addClass('ym-error');
			return false;
		}
	} else if (type == 'select') {
		if (!obj.val()) {
			obj.parents('.ym-fbox:first').addClass('ym-error');
			return false;
		}
	} else if (type == 'isbn') {
		if (!requiredString(obj.val())) {
			obj.val('');
			obj.parent().addClass('ym-error');
			return false;
		} else if (checkLength(obj.val(), '13')) {
			showToast('error', $.i18n.prop('isbn.length.error'));
			obj.parent().addClass('ym-error');
			return false;
		}
	}

	$('#' + name).parents('.ym-fbox:first').removeClass('ym-error');

}

function showToast(type, text, fnct) {
	// notice, warning, error, success
	intervalShowTimerCount = setTimeout(function() {
		intervalShowCount = 0;
	}, (intervalShow * 1.5));
	var time = intervalShow * intervalShowCount;
	setTimeout(function() {
		$().toastmessage('showToast', {
			text : text,
			sticky : false,
			position : 'top-right',
			type : type,
			inEffectDuration : boxInfoShowMS,
			stayTime : boxInfoWaitMS,
			closeText : '',
			close : function() {
				if (fnct) {
					fnct();
				}
			}
		});
	}, time, type, text);
	intervalShowCount++;

}

// funció que carrega la imatge associada a un item
function addImage(e) {
	var file = e.target.files[0], imageType = /image.*/;

	if (!file.type.match(imageType)) {
		showInfo('error', $.i18n.prop('imageFormatError'));
		$('#imageUpload').val("");
		return;
	}

	var reader = new FileReader();
	reader.onload = fileOnload;
	reader.readAsDataURL(file);
}

function fileOnload(e) {
	var result = e.target.result;
	$('#image').attr("src", result);
	$('#imageFile').val(result);
	$('#deleteImage').show();
}

// funció que elimina la imatge seleccionada per a un item
function deleteImage(dialogText) {
	// showWarningDialog(dialogText);
	if (confirm(dialogText)) {
		eraseImage();
	}
}

// borra les dades introduides al formulari
function clearForm() {
	if (confirm($.i18n.prop('clear.form.text'))) {
		setButtons();
		eraseImage();
		$('.ym-error').removeClass('ym-error');
		return true;
	}
	return false;

}

function eraseImage() {
	$('#image').attr("src", "images/books/sample/sampleImage.png");
	$('#imageFile').val("");
	$('#deleteImage').hide();
	$('#imageUpload').val('');
}

function checkSelect(selectName, valueToCheck) {
	var options = $("#" + selectName + " option");
	for ( var i = 0; i < options.length; i++) {
		if ($.trim($(options[i]).text().toLowerCase()) == $.trim(valueToCheck
				.toLowerCase())) {
			showToast('error', $.i18n.prop('duplicated.select.fields'));
			return false;
		}
	}
	return true;
}
function dialogAddSaveButton(selectName) {
	var bValid = true;
	var isNewAuthor = $('#name').length;
	if (isNewAuthor == 0) {
		var editorialName = $('#editorialName').val();
		// comprovem que el camp no estigui buit
		bValid = validate('dialogAdd');
		if (bValid) {
			if (checkSelect(selectName, editorialName)) {
				$('#' + selectName).append(
						'<option value="' + editorialName
								+ '" selected="selected">' + editorialName
								+ '</option>');
				$('#dialogAdd').dialog("close");
				$('#' + selectName).chosen('destroy');
				$('#' + selectName).chosen();
			}
		} else {
			$('#editorialName').parents('.ym-fbox:first').addClass("ym-error");
		}
	} else {
		var name = $('#name').val();
		var surnames = $('#surnames').val();
		var value = surnames + '#' + name;
		bValid = validate('dialogAdd');
		if (bValid) {
			name = surnames + ' ' + name;
			if (checkSelect(selectName, name)) {
				$('#' + selectName).append(
						'<option value="' + value + '" selected="selected">'
								+ name + '</option>');
				$('#dialogAdd').dialog("close");
				$('#' + selectName).chosen('destroy');
				$('#' + selectName).chosen();
			}
		}
	}

}

function showAddDialog(selectName) {
	$(function() {
		$('#dialogAdd').dialog({
			modal : true,
			width : 350,
			buttons : {
				"Save" : function() {
					dialogAddSaveButton(selectName);
				},
				"Cancel" : function() {
					$(this).dialog("close");
					$('#dialogAdd').html("");
				}
			}
		});
	});
}

$(document).ready(function() {

	clickMenu();
	changeActiveLinks();
	setButtons();
	$('#imageUpload').change(function(e) {
		addImage(e);
	});
});